package com.yzq.os.spider.v.listener;

import java.text.ParseException;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.apache.log4j.Logger;
import org.quartz.SchedulerException;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.yzq.os.spider.v.Constants;
import com.yzq.os.spider.v.service.job.SchedulerService;

/**
 * 系统启动监听器，执行Spring上下文常量设置，自动加载定时任务
 * 
 * @author 苑志强(xingyu_yzq@163.com)
 * 
 */
public class SystemStartupListener implements ServletContextListener {

	private static Logger logger = Logger
			.getLogger(SystemStartupListener.class);

	private SchedulerService schedulerService;

	/**
	 * 应用上下文初始化
	 */
	@Override
	public void contextInitialized(ServletContextEvent ctx) {
		//Spring context
		ApplicationContext context = WebApplicationContextUtils
				.getRequiredWebApplicationContext(ctx.getServletContext());
		Constants.setApplicationContext(context);
		//Load scheduler task
		schedulerService = Constants.getApplicationContext().getBean(
				"schedulerService", SchedulerService.class);
		try {
			schedulerService.putCleanQueryUrlTask();
			schedulerService.putLocalCrawlTask();
			schedulerService.startScheduler();
		} catch (SchedulerException e) {
			logger.error("", e);
		} catch (ParseException e) {
			logger.error("", e);
		}
	}

	/**
	 * 应用上下文销毁
	 */
	@Override
	public void contextDestroyed(ServletContextEvent ctx) {
		schedulerService.shutdownScheduler();
	}
}
